package dk.modified.reshary;

import java.util.Map;

import android.app.Activity;
import android.content.Context;
import android.graphics.drawable.BitmapDrawable;
import android.os.Bundle;
import android.view.Gravity;
import android.view.LayoutInflater;
import android.view.View;
import android.view.View.OnClickListener;
import android.view.ViewGroup;
import android.widget.Button;
import android.widget.EditText;
import android.widget.PopupWindow;
import android.widget.TextView;
import android.widget.Toast;

import com.google.android.gms.analytics.GoogleAnalytics;
import com.google.android.gms.analytics.HitBuilders;
import com.google.android.gms.analytics.Tracker;
import com.loopj.android.http.AsyncHttpResponseHandler;
import com.loopj.android.http.RequestParams;

import dk.modified.reshary.GlobalState.TrackerName;

public class LoginScreen extends Activity {

	private PopupWindow resetpwPopup;
	private View popup_shadow;
	private Button cmd_login;

	@Override
	protected void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		setContentView(R.layout.login_screen);
	    Tracker t = ((GlobalState) getApplication()).getTracker(
		        TrackerName.APP_TRACKER);
		    t.setScreenName("Reshary LoginScreen");
		    t.send(new HitBuilders.AppViewBuilder().build());
		cmd_login = (Button) findViewById(R.id.tv_login);
		popup_shadow = (View) findViewById(R.id.popup_shadow);
	}

	public void loginClick(View v) {
		// DO STUFF
		// // new HttpPostTask().execute();
		cmd_login.setEnabled(false);
		PostLogin();
	}

	public void resetpassClick(View v) {
		popup_shadow.setVisibility(View.VISIBLE);

		initiatePopupWindowResetPass();
	}

	@SuppressWarnings("deprecation")
	private void initiatePopupWindowResetPass() {
		try {
			// We need to get the instance of the LayoutInflater
			LayoutInflater inflater = (LayoutInflater) this
					.getSystemService(Context.LAYOUT_INFLATER_SERVICE);
			View layout = inflater.inflate(R.layout.post_popup,
					(ViewGroup) findViewById(R.id.popup_element));
			resetpwPopup = new PopupWindow(layout,
					ViewGroup.LayoutParams.WRAP_CONTENT,
					ViewGroup.LayoutParams.WRAP_CONTENT, true);
			resetpwPopup.setBackgroundDrawable(new BitmapDrawable());
			resetpwPopup.setOutsideTouchable(true);

			TextView txt_title = (TextView) layout.findViewById(R.id.txt_title);
			String text = getResources().getString(R.string.resend_email);
			txt_title.setText(text);
			resetpwPopup.showAtLocation(layout, Gravity.CENTER, 0, 0);

			Button btn_send_popup = (Button) layout
					.findViewById(R.id.btn_ok_popup);
			final EditText txt_email = (EditText) layout
					.findViewById(R.id.txt_email);

			resetpwPopup
					.setOnDismissListener(new PopupWindow.OnDismissListener() {

						@Override
						public void onDismiss() {
							resetpwPopup.dismiss();
							resetpwPopup = null;
							popup_shadow.setVisibility(View.GONE);
							// end may TODO anything else
						}
					});

			btn_send_popup.setOnClickListener(new OnClickListener() {
				public void onClick(View v) {
					String email = txt_email.getText().toString();
					// queue.add(postRequestResetPassword);
					PostResendPassword(email);
					resetpwPopup.dismiss();
					resetpwPopup = null;

				}
			});

		} catch (Exception e) {
			e.printStackTrace();
		}
	}

	public void PostResendPassword(String email) {

		RequestParams params = new RequestParams();
		params.put("email", email);

		ResharyRestClient.post("resetpass/", params,
				new AsyncHttpResponseHandler() {

					@Override
					public void onFailure(Throwable error, String content) {
						Toast.makeText(
								getApplicationContext(),
								getResources()
										.getString(R.string.network_error),
								Toast.LENGTH_LONG).show();
					}

					@Override
					public void onSuccess(String content) {
						Map<String, String> postResponse = Util
								.newformatResponse(content);
						if (postResponse.containsKey("status")) {
							if (postResponse.get("status").equals("success")) {
								Toast.makeText(getApplicationContext(),
										"Email with new password sent",
										Toast.LENGTH_LONG).show();
							} else {
								Toast.makeText(getApplicationContext(),
										postResponse.get("status").toString(),
										Toast.LENGTH_LONG).show();
							}
						}
					}

				}, this);
	}

	public void PostLogin() {
		EditText txt_username = (EditText) findViewById(R.id.txtusername);
		String username = txt_username.getText().toString().trim();
		EditText txt_password = (EditText) findViewById(R.id.txtpassword);
		String password = txt_password.getText().toString().trim();
		RequestParams params = new RequestParams();
		params.put("username", username);
		params.put("pass", password);

		ResharyRestClient.post("login/", params,
				new AsyncHttpResponseHandler() {

					@Override
					public void onFailure(Throwable error, String content) {
						cmd_login.setEnabled(true);
						Toast.makeText(
								getApplicationContext(),
								getResources()
										.getString(R.string.network_error),
								Toast.LENGTH_LONG).show();
					}

					@Override
					public void onSuccess(String content) {
						cmd_login.setEnabled(true);
						Map<String, String> postResponse = Util
								.newformatResponse(content);
						if (postResponse.containsKey("status")) {
							if (postResponse.get("status").equals("success")) {
								Util.sharedPrefsPutLogin(
										getApplicationContext(), postResponse);
								Util.intentLogin(getApplicationContext());
							} else {
								Toast.makeText(
										getApplicationContext(),
										getResources()
												.getString(
														R.string.usernameorpass_invalid),
										Toast.LENGTH_LONG).show();
							}

						}
					}

				}, this);
	}

	@Override
	public void onBackPressed() {
		finish();
		overridePendingTransition(R.anim.right_out, R.anim.left_in);
	}

}
